import { isArray } from 'lodash-es';
import { ref, type Ref } from 'vue';
import type { TreeDataArr } from '../types/treeType';

// 元素是否超标
export function isBeyond(e: any): boolean {
  const ev = e;
  const textRange = (el: any) => {
    const textContent = el;
    const targetW = textContent.getBoundingClientRect().width;
    const range = document.createRange();
    range.setStart(textContent, 0);
    range.setEnd(textContent, textContent.childNodes.length);
    const rangeWidth = range.getBoundingClientRect().width;
    return rangeWidth.toFixed(3) < targetW.toFixed(3);
  };
  return textRange(ev.target);
}
// 获取数据所在同级数据
export function getDataPeer(treeData: Ref<TreeDataArr[]>, key: string): Ref<TreeDataArr[]> {
  const keys = key.split('-');
  // console.log('keys', keys)
  const data = ref<TreeDataArr[]>([]);
  data.value = treeData.value;
  keys.forEach((e: string, index: number) => {
    if (keys.length - 1 != index) {
      const one: any = data.value.filter((fil) => e == fil.id);
      if (one.length) {
        data.value = one[0].children || [];
      }
    }
  });
  return data;
}
// 获取所有key
export function getKesArr(data: TreeDataArr[]): string[] {
  const arr: string[] = [];
  data.forEach((one: TreeDataArr) => {
    arr.push(one.key as string);
    if (isArray(one.children) && one.children.length) {
      arr.push(...getKesArr(one.children));
    }
  });
  return arr;
}

export function setKeyString(data: string[], index: number): string {
  let str = '';
  for (let i = 0; i < index + 1; i++) {
    str += '-' + data[i];
  }
  const strS = str.substring(1);
  console.log('strS', strS);

  return strS;
}
// 数据处理
export function treeDataSeal(
  res: any,
  props = {
    title: 'name',
    key: 'id',
    children: 'children',
  },
  keys?: string,
) {
  const dataArr: TreeDataArr[] = [];
  const keysArr: string[] = [];
  isArray(res) &&
    res.forEach((e: any) => {
      e.title = e[props.title];
      e.key = keys ? keys + e[props.key] : e[props.key].toString();
      keysArr.push(e.key);
      if (isArray(e[props.children]) && e[props.children].length) {
        e[props.children] = treeDataSeal(e[props.children], props, e.key + '-').dataArr;
        keysArr.push(...treeDataSeal(e[props.children], props, e.key + '-').keysArr);
      }
      dataArr.push(e);
    });
  return { dataArr, keysArr };
}
// 根据id数组获取key数组
export function idsGetKeys(data: TreeDataArr[], ids: string[]): string[] {
  let keysArr: string[] = [];
  isArray(data) &&
    data.forEach((e: TreeDataArr) => {
      if (ids.includes((e.id as any).toString())) {
        keysArr.push(e.key);
      }
      if (isArray(e.children) && e.children.length) {
        keysArr.push(...idsGetKeys(e.children, ids));
      }
    });
  return keysArr;
}
